﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.Input;
using System.Windows.Input;
using CommunityToolkit.Mvvm.ComponentModel;
using System.Net.NetworkInformation;
using mas.Models;
using mas.Views;


namespace mas.ViewModels;

public partial class MainWindowViewModel : ViewModelBase
{
    private readonly UdpService _udpService;
    // 直接暴露UdpService的HeaderDatas（供UI绑定）
    public ObservableCollection<HeaderData> HeaderDatas => _udpService.HeaderDatas;
    
    // 公开UdpService属性，供App.axaml.cs访问以进行清理
    public UdpService UdpService => _udpService;
    
    // 本地IP列表（供下拉框绑定）
    public ObservableCollection<string> LocalIpList { get; } = new();
    // 选中的IP地址（双向绑定）
    [ObservableProperty]
    private string? _selectedIp;

    // 暴露UDP服务属性（供UI绑定）
    public int ImagePort
    {
        get => _udpService.ImagePort;
        set => _udpService.ImagePort = value;
    }

    public int MessagePort
    {
        get => _udpService.MessagePort;
        set => _udpService.MessagePort = value;
    }

    // IsUdpRunning 可通知属性
    public bool IsUdpRunning 
    { 
        get => _udpService.IsRunning; 
        private set => OnPropertyChanged();  // 显式触发变更通知
    }
    
    public string StatusMessage => _udpService.StatusMessage;

    // 命令属性
    public ICommand StartUdpCommand { get; }  // 启动UDP命令
    public ICommand StopUdpCommand { get; }  // 停止UDP命令
    public ICommand OpenLogWindowCommand { get; }  // 日志窗口命令
    
    public ICommand OpenPlotWindowCommand { get; }  // 绘图窗口命令
    
    // Header窗口命令
    [RelayCommand]
    private void OpenHeaderWindow()
    {
        // 传递headers并让HeaderWindow自己创建ViewModel
        var headerWindow = new HeaderWindow(_udpService.HeaderDatas);
        headerWindow.Show();
    }

    public MainWindowViewModel()
    {
        // 初始化UDP服务并订阅事件
        _udpService = new UdpService();
        _udpService.PropertyChanged += (s, e) => OnPropertyChanged(e.PropertyName); // 转发属性变更通知

        // 显式监听 IsRunning 变更并触发UI更新
        _udpService.PropertyChanged += (s, e) => 
        {
            OnPropertyChanged(e.PropertyName);
            if (e.PropertyName == nameof(_udpService.IsRunning))
            {
                IsUdpRunning = _udpService.IsRunning;  // 强制刷新UI绑定
            }
        };
        
        // 初始化命令
        StartUdpCommand = new AsyncRelayCommand(StartUdpAsync, CanStartUdp);
        StopUdpCommand = new RelayCommand(StopUdp);
        OpenLogWindowCommand = new RelayCommand(OpenLogWindow);  // 初始化日志窗口命令
        OpenPlotWindowCommand = new RelayCommand(OpenPlotWindow);  // 绘图窗口命令
        
        // 加载本地IP地址
        LoadLocalIpAddresses();
    }
    
    // 新增：启动条件校验（IP已选择且未运行时可启动）
    private bool CanStartUdp() => !IsUdpRunning && !string.IsNullOrEmpty(SelectedIp);
    
    // 启动UDP（调用服务）
    private async Task StartUdpAsync()
    {
        if (string.IsNullOrEmpty(SelectedIp))
        {
            _udpService.StatusMessage = "请选择本地IP地址";
            return;
        }
    
        await _udpService.StartAsync(SelectedIp!);
        // 启动后更新命令状态（触发CanExecute变更）
        if (StartUdpCommand is IRelayCommand startCommand) startCommand.NotifyCanExecuteChanged();
        if (StopUdpCommand is IRelayCommand stopCommand) stopCommand.NotifyCanExecuteChanged();
    }
    
    // 停止UDP（调用服务）
    private void StopUdp()
    {
        _udpService.Stop();
        // 停止后更新命令状态（触发CanExecute变更）
        if (StartUdpCommand is IRelayCommand startCommand) startCommand.NotifyCanExecuteChanged();
        if (StopUdpCommand is IRelayCommand stopCommand) stopCommand.NotifyCanExecuteChanged();
    }
    
    // 加载本地IP地址列表
    private void LoadLocalIpAddresses()
    {
        LocalIpList.Clear();
        try
        {
            // 获取所有网络接口的IPv4地址
            var ipv4Addresses = NetworkInterface.GetAllNetworkInterfaces()
                .Where(nic => nic.OperationalStatus == OperationalStatus.Up)
                .SelectMany(nic => nic.GetIPProperties().UnicastAddresses)
                .Where(addr => addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                .Select(addr => addr.Address.ToString())
                .Where(ip => !ip.StartsWith("127."))  // 排除回环地址
                .Distinct();
    
            foreach (var ip in ipv4Addresses)
            {
                LocalIpList.Add(ip);
            }
    
            // 如果有IP地址，自动选择第一个
            if (LocalIpList.Any())
            {
                SelectedIp = LocalIpList.First();
            }
        }
        catch (Exception ex)
        {
            // 异常处理：添加错误信息到日志
            _udpService.LogMessages.Add(new LogMessage(LogLevel.Error, $"加载IP地址失败: {ex.Message}"));
        }
    }
    
    // 日志窗口
    private void OpenLogWindow()
    {
        var logWindow = new LogWindow
        {
            DataContext = new LogWindowViewModel(_udpService)
        };
        logWindow.Show();
    }
    private void OpenPlotWindow()
    {
        var plotWindow = new PlotWndow
        {
            DataContext = new PlotWindowViewModel(_udpService) // 注入UdpService
        };
        plotWindow.Show();
    }
}
